<?php

  //
  // Memorii Web
  // script/login.php
  //
  // User login.
  //
  
  define("MII_API_LOGIN_ERROR", 0);
  define("MII_API_LOGIN_SUCCESS", 1);
  define("MII_API_LOGIN_ERROR_FAIL", 2);
  define("MII_API_LOGIN_ERROR_ACTIVATION", 3);
  
  function mii_login($email, $password_md5) {
  	$ret = MII_API_LOGIN_ERROR;
  	
		// Fields aren't empty.
    if( $email!="" && $password_md5!="" ) {
      
      // Identification test (todo)
      $db_connection = db_connect();
      $db_result = db_test_login($db_connection, $email, $password_md5);
      if( $db_result ) {
      	$ret = MII_API_LOGIN_SUCCESS;
      }
      else {
      	$db_result = db_test_login_waiting_validation($db_connection, $email, $password_md5);
    	  if( $db_result )
    	    $ret = MII_API_LOGIN_ERROR_ACTIVATION;
    	  else
    	  	$ret = MII_API_LOGIN_ERROR_FAIL;
      }
      db_disconnect($db_connection);
    }
    
    return $ret;
  }
  
  function login(&$msg) {
  	// Default value
	  $success = false;
	    
	  // We get what we need
	  if( isset($_POST['email']) && isset($_POST['password']) ) {
	    $email       	= $_POST['email'];
	    $password     = $_POST['password'];
	    $password_md5 = md5($password);
	    
	    $ret = mii_login($email, $password_md5);
	    
	    if( $ret==MII_API_LOGIN_SUCCESS ) {
	    	$_SESSION['email'] = $email;
	     	$_SESSION['password_md5'] = $password_md5;
      	$db_connection = db_connect();
	     	$_SESSION['current_folder_id'] = db_get_root_folder_id($db_connection, $email, $password_md5);
	      db_disconnect($db_connection);
	      
	      $success = true;
	    }
	    elseif( $ret==MII_API_LOGIN_ERROR_ACTIVATION ) {
	 			$msg = 'Your account is waiting for activation. Please check your mailbox.';
				// TODO: Send another email
	   	}
	   	else {
	   		$msg = 'Identification failed.';
	   	}
	  }
	  
	  return $success;
  }
?>